package com.hzya.frame.utils.core.action;

import com.hzya.frame.system.dictionaryshop.entity.DictionaryShopEntity;
import com.hzya.frame.system.dictionaryshop.service.IDictionaryShopService;
import com.hzya.frame.utils.common.Constants;
import com.hzya.frame.utils.core.annotation.Dictionary;
import com.hzya.frame.utils.core.entity.BaseEntity;
import com.hzya.frame.utils.core.entity.JsonResultEntity;
import com.hzya.frame.utils.core.page.PageInfo;
import com.hzya.frame.utils.help.BeanHelper;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cglib.beans.BeanMap;
import org.springframework.context.support.ApplicationObjectSupport;

import java.lang.reflect.Field;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * @author 郭军辉
 * <p>
 * 2016年12月14日下午5:20:51
 */

public class DefaultController extends ApplicationObjectSupport {

    protected Logger logger = LogManager.getLogger(getClass());
    @Autowired
    private IDictionaryShopService dictionaryPlatformService;

    private Map<String, DictionaryShopEntity> dictionaryCachedMap = Collections.EMPTY_MAP;

    private Long currentTime = System.currentTimeMillis();

    /**
     * 请求失败
     *
     * @param type    类型
     * @param message 提示信息
     * @return
     */
    public JsonResultEntity getFailureMessageEntity(String message, String type) {
        return new JsonResultEntity(message, type, false);
    }

    /**
     * 请求成功
     *
     * @param type    类型
     * @param message 提示消息
     * @param mo      返回对象
     * @return
     */
    public JsonResultEntity getSuccessMessageEntity(String message, String type, Object mo) {
        return new JsonResultEntity(message, type, true, mo);
    }

    /**
     * 请求成功
     *
     * @param type    类型
     * @param message 提示消息
     * @return
     */
    public JsonResultEntity getSuccessMessageEntity(String message, String type) {
        return new JsonResultEntity(message, type, true);
    }

    /**
     * 回填数据字典说明【column_content】
     *
     * @param targetObj
     * @return
     */
    public Object fixDictionaryContent(Object targetObj) {
        if (null == targetObj)
            return null;
        Map<String, DictionaryShopEntity> dictionaryCachedMap = getCachedMap();
        Class targetClass = targetObj.getClass();
        Field[] fields = targetClass.getDeclaredFields();
        StringBuffer dictionaryCachedMapKey = null;
        String column_value = null;
        boolean cglibObjFlag = BeanHelper.isCglibObject(targetObj);
        if (cglibObjFlag) {
            fields = targetClass.getSuperclass().getDeclaredFields();
        }
        for (int j = 0; j < fields.length; j++) {
            Field field = (Field) fields[j];
            Object tempObj = BeanHelper.getPropertyValue(field.getName(), targetObj);
            if (tempObj instanceof BaseEntity && !(tempObj instanceof DictionaryShopEntity)) {
                fixDictionaryContent(tempObj);
            } else {
                if (field.isAnnotationPresent(Dictionary.class)) {
                    Dictionary dictionary = field.getAnnotation(Dictionary.class);
                    if (dictionary != null && !"".equals(dictionary.tab_name())
                            && !"".equals(dictionary.column_name())) {
                        dictionaryCachedMapKey = new StringBuffer();
                        dictionaryCachedMapKey.append(dictionary.tab_name());
                        dictionaryCachedMapKey.append("#" + dictionary.column_name());
                        Object dictionaryField = BeanHelper.getPropertyValue(field.getName(), targetObj);
                        /** 如果数据字典项不为空或null **/
                        if (null != dictionaryField && !"".equals(dictionaryField)) {
                            boolean isObj = dictionaryField instanceof DictionaryShopEntity;
                            if (isObj) {
                                column_value = (String) BeanHelper.getPropertyValue("column_value", dictionaryField);
                            } else {
                                column_value = (String) BeanHelper.getPropertyValue(field.getName(), targetObj);
                            }
                            dictionaryCachedMapKey.append("#" + column_value);

                            DictionaryShopEntity DictionaryShopEntity = dictionaryCachedMap
                                    .get(dictionaryCachedMapKey.toString());
                            if (null != DictionaryShopEntity) {
                                if (cglibObjFlag) {
                                    BeanMap beanMap = BeanMap.create(targetObj);
                                    beanMap.put(field.getName(), isObj == true ? DictionaryShopEntity
                                            : DictionaryShopEntity.getColumn_content());
                                } else {
                                    if (isObj) {
                                        BeanHelper.setPropertyValue(targetObj, field.getName(),
                                                DictionaryShopEntity);
                                    } else {
                                        BeanHelper.setPropertyValue(targetObj, field.getName(),
                                                DictionaryShopEntity.getColumn_content());
                                    }
                                }
                            }

                        }
                    }
                }
            }
        }

        return targetObj;
    }

    public Map<String, DictionaryShopEntity> getCachedMap() {
        if (dictionaryCachedMap.isEmpty())
            dictionaryCachedMap = dictionaryPlatformService.createDictionaryCacheMap();
        if (System.currentTimeMillis() - Constants.currentTime >= 60000) {
            dictionaryCachedMap = dictionaryPlatformService.createDictionaryCacheMap();
        }

        return dictionaryCachedMap;
    }

    /**
     * @param targetList
     * @return
     */
    public List<?> fixDictionaryContent(List<?> targetList) {
        if (null != targetList && 0 < targetList.size()) {
            for (int i = 0; i < targetList.size(); i++) {
                Object tempEntity = targetList.get(i);
                fixDictionaryContent(tempEntity);
            }
        }
        return targetList;
    }

    /**
     * @param pageObj
     * @return
     */
    public PageInfo fixDictionaryContent(PageInfo pageObj) {
        if (null != pageObj) {
            List dataList = pageObj.getRows();
            if (null != dataList)
                fixDictionaryContent(dataList);
        }

        return pageObj;
    }

    /***
     * 起作用，这个是用到创建人员和修改人员
     *
     * @param entity
     * @return
     * @throws Exception
     */
    public BaseEntity bindCommonProperies(BaseEntity entity) throws Exception {
        if (entity.getId() == null) {
            entity.setCreate_user_id(SessionContext.getCurrentUser().getId());
            entity.setModify_user_id(SessionContext.getCurrentUser().getId());
        } else {
            entity.setModify_user_id(SessionContext.getCurrentUser().getId());
        }
        return entity;
    }
}
